<?php
/**
 * PhalApi_Helper_ApiDesc - 在线接口描述查看 - 辅助类
 *
 * @package     PhalApi\Helper
 * @license     http://www.phalapi.net/license GPL 协议
 * @link        http://www.phalapi.net/
 * @author      dogstar <chanzonghuang@gmail.com> 2015-05-30
 */

class PhalApi_Helper_ApiDesc {
    public function SafeFilter (&$arr)
    {

        $ra=Array('/([\x00-\x08,\x0b-\x0c,\x0e-\x19])/','/script/','/javascript/','/vbscript/','/expression/','/applet/','/meta/','/xml/','/blink/','/link/','/style/','/embed/','/object/','/frame/','/layer/','/title/','/bgsound/','/base/','/onload/','/onunload/','/onchange/','/onsubmit/','/onreset/','/onselect/','/onblur/','/onfocus/','/onabort/','/onkeydown/','/onkeypress/','/onkeyup/','/onclick/','/ondblclick/','/onmousedown/','/onmousemove/','/onmouseout/','/onmouseover/','/onmouseup/','/onunload/');

        if (is_array($arr))
        {
            foreach ($arr as $key => $value)
            {
                if (!is_array($value))
                {
                    if (!get_magic_quotes_gpc())             //不对magic_quotes_gpc转义过的字符使用addslashes(),避免双重转义。
                    {
                        $value  = addslashes($value);           //给单引号（'）、双引号（"）、反斜线（\）与 NUL（NULL 字符）加上反斜线转义
                    }
                    $value       = preg_replace($ra,'',$value);     //删除非打印字符，粗暴式过滤xss可疑字符串
                    $arr[$key]     = htmlentities(strip_tags($value)); //去除 HTML 和 PHP 标记并转换为 HTML 实体
                }
                else
                {
                    $this->SafeFilter($arr[$key]);
                }
            }
        }
    }
    public function render() {
        $service = DI()->request->get('service', 'Default.Index');
        $this->SafeFilter($service);
        $rules = array();
        $returns = array();
        $description = '';
        $descComment = '//请使用@desc 注释';

        $typeMaps = array(
            'string' => '字符串',
            'int' => '整型',
            'float' => '浮点型',
            'boolean' => '布尔型',
            'date' => '日期',
            'array' => '数组',
            'fixed' => '固定值',
            'enum' => '枚举类型',
            'object' => '对象',
            'mobile'  => '国内手机',
            'email'   => '邮箱',
            'uri'     => '网址',
            'file'    => '文件',
        );

        try {
            $api = PhalApi_ApiFactory::generateService(false);
            $rules = $api->getApiRules();
        } catch (PhalApi_Exception $ex){
            $service .= ' - ' . $ex->getMessage();
            include dirname(__FILE__) . '/api_desc_tpl.php';
            return;
        }
        $apiCommonRules = DI()->config->get('app.apiCommonRules', array());
        if (!empty($apiCommonRules) && is_array($apiCommonRules)) {
            $rules = array_merge($apiCommonRules, $rules);
        }

        list($className, $methodName) = explode('.', $service);
        $className = 'Api_' . $className;

        $rMethod = new ReflectionMethod($className, $methodName);
        $docComment = $rMethod->getDocComment();
        $docCommentArr = explode("\n", $docComment);

        foreach ($docCommentArr as $comment) {
            $comment = trim($comment);

            //标题描述
            if (empty($description) && strpos($comment, '@') === false && strpos($comment, '/') === false) {
                $description = substr($comment, strpos($comment, '*') + 1);
                continue;
            }

            //@desc注释
            $pos = stripos($comment, '@desc');
            if ($pos !== false) {
                $descComment = substr($comment, $pos + 5);
                continue;
            }

            //@return注释
            $pos = stripos($comment, '@return');
            if ($pos !== false) {
                $returnCommentArr = explode(' ', substr($comment, $pos + 8));
                //将数组中的空值过滤掉，同时将需要展示的值返回
                $returnCommentArr = array_values(array_filter($returnCommentArr));
                if (count($returnCommentArr) < 2) {
                    continue;
                }
                if (!isset($returnCommentArr[2])) {
                    $returnCommentArr[2] = '';	//可选的字段说明
                } else {
                    //兼容处理有空格的注释
                    $returnCommentArr[2] = implode(' ', array_slice($returnCommentArr, 2));
                }
                $returns[] = $returnCommentArr;
                continue;
            }
            //@throws注释
            $pos = stripos($comment, '@throws');
            if ($pos === false) {
                continue;
            }
            $throwsCommentArr = explode(' ', substr($comment, $pos + 8));
            //将数组中的空值过滤掉，同时将需要展示的值返回
            $throwsCommentArr = array_values(array_filter($throwsCommentArr));
            if (count($throwsCommentArr) < 2) {
                continue;
            }
            if (!isset($throwsCommentArr[2])) {
                $throwsCommentArr[2] = '';	//可选的字段说明
            } else {
                //兼容处理有空格的注释
                $throwsCommentArr[2] = implode(' ', array_slice($throwsCommentArr, 2));
            }
            $throws[] = $throwsCommentArr;


        }
        if($descComment=='')$descComment = '//请使用@desc 注释';
        include dirname(__FILE__) . '/api_desc_tpl.php';
    }
}
